package cn.iocoder.yudao.module.vos.service.marketinglistlog;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.vos.controller.admin.marketinglistlog.vo.*;
import cn.iocoder.yudao.module.vos.dal.dataobject.marketinglistlog.MarketingListLogDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.vos.dal.mysql.marketinglistlog.MarketingListLogMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.vos.enums.ErrorCodeConstants.*;

/**
 * 营销名单日志表（含应答状态） Service 实现类
 *
 * @author shijun
 */
@Service
@Validated
public class MarketingListLogServiceImpl implements MarketingListLogService {

    @Resource
    private MarketingListLogMapper marketingListLogMapper;

    @Override
    public Long createMarketingListLog(MarketingListLogSaveReqVO createReqVO) {
        // 插入
        MarketingListLogDO marketingListLog = BeanUtils.toBean(createReqVO, MarketingListLogDO.class);
        marketingListLogMapper.insert(marketingListLog);

        // 返回
        return marketingListLog.getId();
    }

    @Override
    public void updateMarketingListLog(MarketingListLogSaveReqVO updateReqVO) {
        // 校验存在
        validateMarketingListLogExists(updateReqVO.getId());
        // 更新
        MarketingListLogDO updateObj = BeanUtils.toBean(updateReqVO, MarketingListLogDO.class);
        marketingListLogMapper.updateById(updateObj);
    }

    @Override
    public void deleteMarketingListLog(Long id) {
        // 校验存在
        validateMarketingListLogExists(id);
        // 删除
        marketingListLogMapper.deleteById(id);
    }

    @Override
        public void deleteMarketingListLogListByIds(List<Long> ids) {
        // 删除
        marketingListLogMapper.deleteByIds(ids);
        }


    private void validateMarketingListLogExists(Long id) {
        if (marketingListLogMapper.selectById(id) == null) {
            throw exception(MARKETING_LIST_LOG_NOT_EXISTS);
        }
    }

    @Override
    public MarketingListLogDO getMarketingListLog(Long id) {
        return marketingListLogMapper.selectById(id);
    }

    @Override
    public PageResult<MarketingListLogDO> getMarketingListLogPage(MarketingListLogPageReqVO pageReqVO) {
        return marketingListLogMapper.selectPage(pageReqVO);
    }

    /** upsert：仅按 (tenant + phoneE164 + listDate) 查重；命中更新三字段；否则插入 */
    /** upsert：仅按 (tenant + phoneE164 + listDate) 查重；命中更新三字段（listLevel 为 String） */
    @Override
    public Long saveOrUpdateIgnoreResponse(MarketingListLogDO vo) {
        if (StrUtil.isBlank(vo.getPhoneE164())) {
            throw new IllegalArgumentException("phoneE164 不能为空");
        }
        if (StrUtil.isBlank(vo.getListDate())) {
            throw new IllegalArgumentException("listDate 不能为空(yyyy-MM-dd)");
        }
        Long id = marketingListLogMapper.selectIdByTenantPhoneDate(
                vo.getRechargeTenantId(), vo.getPhoneE164(), vo.getListDate());

        if (id == null) {
            marketingListLogMapper.insert(vo);
            return vo.getId();
        } else {
            marketingListLogMapper.updateWithoutResponseById(
                    id,
                    vo.getScore(),
                    vo.getPhoneTags(),
                    vo.getListLevel(), // String
                    vo.getMarketingTools() // 新增字段
            );
            return id;
        }
    }


    public List<MarketingListLogDO> getConvertedLogs(Long tenantId, Integer responseState) {
        return marketingListLogMapper.selectList(new LambdaQueryWrapperX<MarketingListLogDO>()
                .eq(MarketingListLogDO::getRechargeTenantId, tenantId)
                .eq(MarketingListLogDO::getResponseState, responseState));
    }

}